/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrame.java
 *
 * Created on 20/05/2014, 12:48:00 PM
 */
package csvreader.view;

import csvreader.service.DaoContact;
import csvreader.controller.ResetText;
import csvreader.view.SearchPanel;
import csvreader.view.AddPanel;
import csvreader.model.Contact;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javafx.scene.input.DataFormat.URL;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author 11.6711
 */
public class MainFrame extends javax.swing.JFrame {

    private File file;
    private static DaoContact daoMhs;
    private AddPanel addPanel;
    private SearchPanel searchPanel;
    private static MainFrame mainFrame;
    private static DefaultTableModel dm;
    URL url = getClass().getResource("/csvreader/data.bat");
    //"C:\\Users\\User\\Documents\\NetBeansProjects\\phonebookCSV\\src\\csvreader\\data.csv"
    /**
     * Creates new form JFrame
     */
    public MainFrame() throws IOException, ClassNotFoundException {
        initComponents();
        initVar();
        setLocationRelativeTo(this);
        setVisible(true);
        try {
            file = new File(url.toURI());
            daoMhs = new DaoContact(file);
            loadData();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (URISyntaxException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } 

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        buttonTambah = new javax.swing.JButton();
        buttonBrowse = new javax.swing.JButton();
        textFieldSearch = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        progressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setPreferredSize(new java.awt.Dimension(486, 60));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        buttonTambah.setText("Tambah Data");
        buttonTambah.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                buttonTambahComponentShown(evt);
            }
        });
        buttonTambah.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonTambahActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(buttonTambah, gridBagConstraints);

        buttonBrowse.setText("Hapus Data");
        buttonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(0, 47, 0, 0);
        jPanel1.add(buttonBrowse, gridBagConstraints);

        textFieldSearch.setPreferredSize(new java.awt.Dimension(280, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        jPanel1.add(textFieldSearch, gridBagConstraints);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nama", "Telepon 1", "Telepon 2", "Telepon 3", "Email", "Keterangan"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.getTableHeader().setReorderingAllowed(false);
        table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                tablePropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel2.setLayout(new java.awt.GridBagLayout());

        progressBar1.setForeground(new java.awt.Color(0, 0, 0));
        progressBar1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        progressBar1.setIndeterminate(true);
        progressBar1.setString("Running......");
        progressBar1.setStringPainted(true);
        jPanel2.add(progressBar1, new java.awt.GridBagConstraints());

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void buttonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseActionPerformed
    if (table.getSelectedRow()>=0) {
        String nama = (String) table.getValueAt(table.getSelectedRow(), 0);
        String telepon1 = (String) table.getValueAt(table.getSelectedRow(), 1);
        String telepon2 = (String) table.getValueAt(table.getSelectedRow(), 2);
        String telepon3 = (String) table.getValueAt(table.getSelectedRow(), 3);
        String email = (String) table.getValueAt(table.getSelectedRow(), 4);
        String keterangan = (String) table.getValueAt(table.getSelectedRow(), 0);
        try {
            daoMhs.deleteContact(new Contact(nama, telepon1, telepon2, telepon3, email, keterangan));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        loadData();
    }else{
         JOptionPane.showMessageDialog(rootPane, "Pilih row dulu", "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_buttonBrowseActionPerformed

    private void buttonTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTambahActionPerformed
        ResetText.resetJTextField(addPanel);
        addPanel.setLocationRelativeTo(this);
        addPanel.setVisible(true);
    }//GEN-LAST:event_buttonTambahActionPerformed

    private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tablePropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_tablePropertyChange

    private void buttonTambahComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_buttonTambahComponentShown
        
    }//GEN-LAST:event_buttonTambahComponentShown
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBrowse;
    private javax.swing.JButton buttonTambah;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JProgressBar progressBar1;
    private javax.swing.JTable table;
    private javax.swing.JTextField textFieldSearch;
    // End of variables declaration//GEN-END:variables

    private void initVar() {
        addPanel = new AddPanel(this, rootPaneCheckingEnabled);
        dm = (DefaultTableModel) table.getModel();
        searchPanel = new SearchPanel(this, rootPaneCheckingEnabled);

        //file = new File("data.csv");
        //daoMhs = new DaoContact(file);
    }

    public static DaoContact getDaoMhs() {
        return daoMhs;
    }

    public static MainFrame getMainFrame() throws IOException, ClassNotFoundException {
        if (mainFrame == null) {
            mainFrame = new MainFrame();
        }
        return mainFrame;
    }

    public AddPanel getAddPanel() {
        return addPanel;
    }

    public void loadData() {
        while (dm.getRowCount() > 0) {
            dm.removeRow(0);
        }
        for (Contact c : daoMhs.getSetContact()) {
            dm.addRow(new Object[]{c.getNama(), c.getTelepon1(), c.getTelepon2(), c.getTelepon3(), c.getEmail(), c.getKeterangan()});
        }
    }

    public JTable getTable() {
        return table;
    }

    public SearchPanel getSearchPanel() {
        return searchPanel;
    }
}
